#include "search.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

// 辅助函数：不区分大小写比较
static int strcasecmp_custom(const char* a, const char* b, size_t len) {
    for (size_t i = 0; i < len; i++) {
        if (tolower(a[i]) != tolower(b[i])) {
            return tolower(a[i]) - tolower(b[i]);
        }
    }
    return 0;
}

SearchResult* search_in_page(const PageContent* page, const char* keyword) {
    if (!page || !page->content || !keyword) return NULL;

    size_t keyword_len = strlen(keyword);
    if (keyword_len == 0) return NULL;

    // 预分配结果数组（最多100个匹配）
    SearchResult* results = malloc(sizeof(SearchResult) * 101);
    int count = 0;

    const char* content = page->content;
    size_t content_len = page->length;

    // 遍历内容查找匹配
    for (size_t i = 0; i <= content_len - keyword_len; i++) {
        if (strcasecmp_custom(&content[i], keyword, keyword_len) == 0) {
            results[count].start_pos = i;
            results[count].length = keyword_len;
            count++;
            if (count >= 100) break; // 限制最大匹配数
        }
    }

    // 结束标记
    results[count].start_pos = -1;
    results[count].length = 0;

    return results;
}

void free_search_results(SearchResult* results) {
    free(results);
}